#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>

#define FIFO_FILE "/tmp/my_fifo"
#define MAX_BUFFER_SIZE 256

int main() {
    int fd;
    char buffer[MAX_BUFFER_SIZE];
    int ret;

    // 创建命名管道
    ret = mkfifo(FIFO_FILE, 0666);
    if (ret < 0 && errno != EEXIST) {
        perror("mkfifo failed");
        exit(EXIT_FAILURE);
    }

    printf("Writer: FIFO created or already exists\n");
    printf("Writer: Opening FIFO for writing...\n");

    // 打开管道进行写操作
    fd = open(FIFO_FILE, O_WRONLY);
    if (fd < 0) {
        perror("open FIFO failed");
        exit(EXIT_FAILURE);
    }

    printf("Writer: FIFO opened successfully\n");
    printf("Writer: Enter messages to send (type 'exit' to quit):\n");

    // 循环读取用户输入并写入管道
    while (1) {
        printf("Writer> ");
        fgets(buffer, MAX_BUFFER_SIZE, stdin);
        
        // 移除换行符
        buffer[strcspn(buffer, "\n")] = '\0';
        
        // 如果用户输入exit，则退出循环
        if (strcmp(buffer, "exit") == 0) {
            printf("Writer: Exiting...\n");
            break;
        }
        
        // 写入管道
        ret = write(fd, buffer, strlen(buffer) + 1);
        if (ret < 0) {
            perror("write failed");
            close(fd);
            exit(EXIT_FAILURE);
        }
        
        printf("Writer: Sent message successfully\n");
    }

    // 关闭文件描述符
    close(fd);
    
    // 可选：删除FIFO文件
    // unlink(FIFO_FILE);
    
    printf("Writer: Program terminated\n");
    return 0;
}